<template>
  <div class="papers-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h1>试卷管理</h1>
        <p>创建和管理考试试卷</p>
      </div>
      <div class="header-right">
        <el-button @click="importPaper">
          <i class="fas fa-upload"></i>
          导入试卷
        </el-button>
        <el-button type="primary" @click="createNewPaper">
          <i class="fas fa-plus"></i>
          创建试卷
        </el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div 
        class="stat-card total" 
        :class="{ 'stat-active': statusFilter === '' }"
        @click="handleStatCardClick('total')"
      >
        <div class="stat-icon">
          <i class="fas fa-file-alt"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.total }}</h3>
          <p>总试卷数</p>
        </div>
      </div>
      
      <div 
        class="stat-card active" 
        :class="{ 'stat-active': statusFilter === 'active' }"
        @click="handleStatCardClick('active')"
      >
        <div class="stat-icon">
          <i class="fas fa-play-circle"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.active }}</h3>
          <p>进行中</p>
        </div>
      </div>
      

      
      <div 
        class="stat-card finished" 
        :class="{ 'stat-active': statusFilter === 'finished' }"
        @click="handleStatCardClick('finished')"
      >
        <div class="stat-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.finished }}</h3>
          <p>已结束</p>
        </div>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索试卷名称..."
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        <el-select v-model="statusFilter" placeholder="试卷状态" clearable>
          <el-option label="全部状态" value="" />
          <el-option label="已发布" value="published" />
          <el-option label="进行中" value="active" />
          <el-option label="已结束" value="finished" />
        </el-select>
        <el-select v-model="subjectFilter" placeholder="科目" clearable>
          <el-option label="全部科目" value="" />
          <el-option label="数据结构" value="data-structure" />
          <el-option label="算法设计" value="algorithm" />
          <el-option label="计算机网络" value="network" />
          <el-option label="操作系统" value="os" />
        </el-select>
        <el-select v-model="sortBy" placeholder="排序方式">
          <el-option label="创建时间" value="createTime" />
          <el-option label="试卷名称" value="name" />
          <el-option label="题目数量" value="questionCount" />
          <el-option label="考试时长" value="duration" />
        </el-select>
      </div>
      <div class="search-right">
        <el-button :icon="Refresh" @click="loadPapers">刷新</el-button>
      </div>
    </div>
    
    <!-- 试卷列表 -->
    <div class="papers-grid">
      <div 
        v-for="paper in paginatedPapers" 
        :key="paper.id" 
        class="paper-card"
        :class="paper.status"
      >
        <div class="paper-header">
          <div class="paper-title">
            <h3>{{ paper.name }}</h3>
            <el-tag 
              :type="getStatusTagType(paper.status)"
              size="small"
            >
              {{ getStatusLabel(paper.status) }}
            </el-tag>
          </div>
          <div class="paper-actions">
            <el-dropdown trigger="click">
              <el-button text>
                <i class="fas fa-ellipsis-v"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="editPaper(paper)">
                    <i class="fas fa-edit"></i> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click="previewPaper(paper)">
                    <i class="fas fa-eye"></i> 预览
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="paper.status === 'published'"
                    @click="publishPaperAction(paper)"
                  >
                    <i class="fas fa-paper-plane"></i> 发布
                  </el-dropdown-item>
                  <el-dropdown-item 
                    @click="deletePaperAction(paper)"
                    class="danger"
                  >
                    <i class="fas fa-trash"></i> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div class="paper-content">
          <div class="paper-description">
            <p>{{ paper.description || '暂无描述' }}</p>
          </div>
          
          <div class="paper-meta">
            <div class="meta-item">
              <i class="fas fa-list"></i>
              <span>{{ paper.questionCount }} 题</span>
            </div>
            <div class="meta-item">
              <i class="fas fa-clock"></i>
              <span>{{ paper.duration }} 分钟</span>
            </div>
            <div class="meta-item">
              <i class="fas fa-star"></i>
              <span>{{ paper.totalScore }} 分</span>
            </div>

          </div>
          
          <div class="paper-time">
            <div v-if="paper.startTime" class="time-item">
              <span class="label">开始时间：</span>
              <span class="value">{{ formatDateTime(paper.startTime) }}</span>
            </div>
            <div v-if="paper.endTime" class="time-item">
              <span class="label">结束时间：</span>
              <span class="value">{{ formatDateTime(paper.endTime) }}</span>
            </div>
            <div class="time-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatDateTime(paper.createTime) }}</span>
            </div>
          </div>
          
          <div class="paper-subjects">
            <el-tag 
              v-for="subject in paper.subjects" 
              :key="subject" 
              size="small"
              class="subject-tag"
            >
              {{ getSubjectLabel(subject) }}
            </el-tag>
          </div>
        </div>
        
        <div class="paper-footer">
          <div class="paper-progress" v-if="paper.status === 'active'">
            <div class="progress-info">
              <span>进度：{{ paper.completedCount || 0 }} / {{ paper.totalAssigned || 0 }}</span>
              <span class="percentage">{{ getProgressPercentage(paper) }}%</span>
            </div>
            <el-progress 
              :percentage="getProgressPercentage(paper)"
              :stroke-width="6"
              :show-text="false"
            />
          </div>
          
          <div class="paper-actions-bottom">
            <el-button 
              v-if="paper.status === 'published'"
              size="small" 
              type="primary"
              @click="startExam(paper)"
            >
              开始考试
            </el-button>
            <el-button 
              v-if="paper.status === 'active'"
              size="small" 
              @click="viewResults(paper)"
            >
              查看结果
            </el-button>
            <el-button 
              v-if="paper.status === 'finished'"
              size="small" 
              @click="viewAnalysis(paper)"
            >
              数据分析
            </el-button>
            <el-button 
              size="small" 
              @click="previewPaper(paper)"
            >
              预览
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48]"
        :total="filteredPapers.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 空状态 -->
    <div v-if="filteredPapers.length === 0" class="empty-state">
      <i class="fas fa-file-alt"></i>
      <h3>暂无试卷</h3>
      <p>还没有创建任何试卷，点击上方按钮开始创建</p>
      <el-button type="primary" @click="createNewPaper">
        创建第一份试卷
      </el-button>
    </div>
    
    <!-- 创建/编辑试卷对话框 -->
    <el-dialog
      v-model="showPaperDialog"
      :title="isEditing ? '编辑试卷' : '创建试卷'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="paperFormRef" 
        :model="paperForm" 
        :rules="paperRules" 
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input 
            v-model="paperForm.name" 
            placeholder="请输入试卷名称"
          />
        </el-form-item>
        
        <el-form-item label="试卷描述" prop="description">
          <el-input 
            v-model="paperForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入试卷描述"
          />
        </el-form-item>
        
        <el-form-item label="所属课程" prop="courseId">
          <el-select 
            v-model="paperForm.courseId" 
            placeholder="选择所属课程"
            style="width: 100%"
          >
            <el-option 
              v-for="course in courses" 
              :key="course.courseId" 
              :label="course.courseName" 
              :value="course.courseId" 
            />
          </el-select>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试时长" prop="duration">
              <el-input-number 
                v-model="paperForm.duration" 
                :min="1" 
                :max="300"
                placeholder="分钟"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总分" prop="totalScore">
              <el-input-number 
                v-model="paperForm.totalScore" 
                :min="1" 
                :max="1000"
                placeholder="分数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="考试时间">
          <el-date-picker
            v-model="examTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="试卷设置">
          <el-checkbox-group v-model="paperForm.settings">
            <el-checkbox label="randomOrder">随机题目顺序</el-checkbox>
            <el-checkbox label="showScore">显示分数</el-checkbox>
            <el-checkbox label="allowReview">允许查看答案</el-checkbox>
            <el-checkbox label="preventCheating">防作弊监控</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showPaperDialog = false">取消</el-button>
        <el-button type="primary" @click="savePaper" :loading="saving">
          {{ isEditing ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 试卷预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      title="试卷预览"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="previewPaperData" class="paper-preview">
        <div class="preview-header">
          <h2>{{ previewPaperData.name }}</h2>
          <div class="preview-meta">
            <span>考试时长：{{ previewPaperData.duration }} 分钟</span>
            <span>总分：{{ previewPaperData.totalScore }} 分</span>
            <span>题目数量：{{ previewPaperData.questionCount }} 题</span>
          </div>
          <div class="preview-description">
            <p>{{ previewPaperData.description }}</p>
          </div>
        </div>
        
        <div class="preview-questions">
          <div 
            v-for="(question, index) in previewPaperData.questions" 
            :key="question.id" 
            class="preview-question"
          >
            <div class="question-header">
              <h4>第 {{ index + 1 }} 题 ({{ question.score }} 分)</h4>
              <el-tag :type="getQuestionTypeTag(question.type)">
                {{ getQuestionTypeLabel(question.type) }}
              </el-tag>
            </div>
            
            <div class="question-content">
              <div class="question-text" v-html="question.content"></div>
              
              <!-- 选择题选项 -->
              <div v-if="['single', 'multiple'].includes(question.type)" class="question-options">
                <div 
                  v-for="(option, optIndex) in question.options" 
                  :key="optIndex" 
                  class="option-item"
                >
                  <span class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</span>
                  <span class="option-text">{{ option }}</span>
                </div>
              </div>
              
              <!-- 填空题 -->
              <div v-else-if="question.type === 'fill'" class="fill-blanks">
                <p>请在空白处填入答案</p>
              </div>
              
              <!-- 简答题 -->
              <div v-else-if="question.type === 'essay'" class="essay-area">
                <p>请在下方作答</p>
                <div class="answer-area">（此处为答题区域）</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showPreviewDialog = false">关闭</el-button>
        <el-button type="primary" @click="editPaper(previewPaperData)">
          编辑试卷
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { 
  getPaperList, 
  createPaper, 
  updatePaper, 
  deletePaper
} from '@/api/rbac/admin'
import { getMyCourses } from '@/api/course-management'
import { getMyExamAssignments, deleteExamAssignment } from '@/api/exam/examAssignments'

const searchKeyword = ref('')
const statusFilter = ref('')
const subjectFilter = ref('')
const sortBy = ref('createTime')
const currentPage = ref(1)
const pageSize = ref(12)
const totalPapers = ref(0)
const showPaperDialog = ref(false)
const showPreviewDialog = ref(false)
const isEditing = ref(false)
const saving = ref(false)
const previewPaperData = ref(null)
const paperFormRef = ref()
const examTimeRange = ref([])

const stats = ref({
  total: 0,
  active: 0,
  finished: 0
})

const paperForm = ref({
  name: '',
  description: '',
  courseId: null,
  duration: 120,
  totalScore: 100,
  startTime: '',
  endTime: '',
  settings: ['showScore']
})

const courses = ref([])

const paperRules = {
  name: [
    { required: true, message: '请输入试卷名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  courseId: [
    { required: true, message: '请选择所属课程', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' }
  ],
  totalScore: [
    { required: true, message: '请输入总分', trigger: 'blur' }
  ]
}

const papers = ref([
  {
    id: 1,
    name: '数据结构期末考试',
    description: '涵盖线性表、栈、队列、树、图等核心内容',
    status: 'active',
    subjects: ['data-structure'],
    duration: 120,
    totalScore: 100,
    questionCount: 25,
    participantCount: 45,
    completedCount: 32,
    totalAssigned: 45,
    startTime: '2023-12-01T09:00:00',
    endTime: '2023-12-01T11:00:00',
    createTime: '2023-11-25T10:30:00',
    questions: [
      {
        id: 1,
        type: 'single',
        content: '以下哪种数据结构适合实现递归算法？',
        options: ['队列', '栈', '数组', '链表'],
        score: 4
      },
      {
        id: 2,
        type: 'multiple',
        content: '以下哪些是线性数据结构？',
        options: ['数组', '链表', '栈', '二叉树'],
        score: 6
      }
    ]
  },
  {
    id: 2,
    name: '算法设计与分析',
    description: '算法复杂度分析、排序算法、动态规划等',
    status: 'draft',
    subjects: ['algorithm'],
    duration: 150,
    totalScore: 120,
    questionCount: 30,
    participantCount: 0,
    createTime: '2023-11-28T14:20:00',
    questions: []
  },
  {
    id: 3,
    name: '计算机网络基础',
    description: 'TCP/IP协议、网络层次结构、路由算法',
    status: 'finished',
    subjects: ['network'],
    duration: 90,
    totalScore: 80,
    questionCount: 20,
    participantCount: 38,
    completedCount: 38,
    totalAssigned: 38,
    startTime: '2023-11-20T14:00:00',
    endTime: '2023-11-20T15:30:00',
    createTime: '2023-11-15T16:45:00',
    questions: []
  }
])

const filteredPapers = computed(() => {
  let result = papers.value
  
  if (searchKeyword.value) {
    result = result.filter(p => 
      p.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    result = result.filter(p => p.status === statusFilter.value)
  }
  
  if (subjectFilter.value) {
    result = result.filter(p => p.subjects.includes(subjectFilter.value))
  }
  
  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'createTime':
        return new Date(b.createTime) - new Date(a.createTime)
      case 'name':
        return a.name.localeCompare(b.name)
      case 'questionCount':
        return b.questionCount - a.questionCount
      case 'duration':
        return b.duration - a.duration
      default:
        return 0
    }
  })
  
  return result
})

// 分页后的数据
const paginatedPapers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPapers.value.slice(start, end)
})

const getStatusLabel = (status) => {
  const labels = {
    draft: '草稿',
    published: '已发布',
    active: '进行中',
    finished: '已结束'
  }
  return labels[status] || status
}

const getStatusTagType = (status) => {
  const types = {
    draft: 'info',
    published: 'warning',
    active: 'success',
    finished: 'primary'
  }
  return types[status] || 'info'
}

const getSubjectLabel = (subject) => {
  const labels = {
    'data-structure': '数据结构',
    'algorithm': '算法设计',
    'network': '计算机网络',
    'os': '操作系统',
    'database': '数据库',
    'software-engineering': '软件工程'
  }
  return labels[subject] || subject
}

const getQuestionTypeLabel = (type) => {
  const labels = {
    single: '单选题',
    multiple: '多选题',
    boolean: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return labels[type] || type
}

const getQuestionTypeTag = (type) => {
  const types = {
    single: 'primary',
    multiple: 'success',
    boolean: 'warning',
    fill: 'info',
    essay: 'danger'
  }
  return types[type] || 'primary'
}

const getProgressPercentage = (paper) => {
  if (!paper.totalAssigned || paper.totalAssigned === 0) return 0
  return Math.round((paper.completedCount / paper.totalAssigned) * 100)
}

// 根据考试时间判断状态
const getExamStatus = (assignment) => {
  const now = new Date()
  const startTime = new Date(assignment.startTime)
  const endTime = new Date(assignment.endTime)
  
  if (!assignment.startTime || !assignment.endTime) {
    return 'published'
  }
  
  if (now < startTime) {
    return 'published'
  } else if (now >= startTime && now <= endTime) {
    return 'active'
  } else {
    return 'finished'
  }
}

// 从题目中提取学科信息
const getExamSubjects = (exam) => {
  if (!exam.questions || exam.questions.length === 0) {
    return []
  }
  
  const subjects = new Set()
  exam.questions.forEach(examQuestion => {
    if (examQuestion.question && examQuestion.question.subject) {
      subjects.add(examQuestion.question.subject)
    }
  })
  
  return Array.from(subjects)
}

// 计算总分
const calculateTotalScore = (questions) => {
  if (!questions || questions.length === 0) {
    return 0
  }
  
  // 暂时返回题目数量 * 5 作为总分，实际应该根据每题分值计算
  return questions.length * 5
}

// 更新统计数据
const updateStats = () => {
  const total = papers.value.length
  const published = papers.value.filter(p => p.status === 'published').length
  const active = papers.value.filter(p => p.status === 'active').length
  const finished = papers.value.filter(p => p.status === 'finished').length
  
  stats.value = {
    total,
    active,
    finished
  }
}

// 点击统计卡片筛选对应状态的试卷
const handleStatCardClick = (status) => {
  if (status === 'total') {
    statusFilter.value = ''
  } else {
    statusFilter.value = status
  }
  // 重置到第一页
  currentPage.value = 1
}

const loadPapers = async () => {
  try {
    const response = await getMyExamAssignments()
    if (response && response.code === 200 && response.data) {
      // 将后端数据格式转换为前端需要的格式，过滤掉null值
      papers.value = response.data
        .filter(assignment => assignment && assignment.assignmentId)
        .map(assignment => ({
        id: assignment.assignmentId,
        examId: assignment.examId,
        name: assignment.exam?.title || '未命名考试',
        description: assignment.exam?.description || '暂无描述',
        status: getExamStatus(assignment),
        courseId: assignment.exam?.courseId,
        duration: assignment.exam?.durationMinutes || 0,
        totalScore: assignment.exam?.totalScore || 0,
        questionCount: assignment.exam?.questions ? assignment.exam.questions.length : 0,
        completedCount: 0,
        totalAssigned: 0,
        startTime: assignment.startTime,
        endTime: assignment.endTime,
        createTime: assignment.createdAt,
        questions: assignment.exam?.questions || []
      }))
      totalPapers.value = papers.value.length
      
      // 计算统计数据
      updateStats()
    } else {
      // 如果响应格式不正确，使用空数据但不显示错误
      papers.value = []
      totalPapers.value = 0
      updateStats()
    }
  } catch (error) {
    console.warn('加载试卷列表失败，可能是后端接口未实现:', error)
    // 静默处理错误，不影响用户状态
    papers.value = []
    totalPapers.value = 0
    updateStats()
    // 只在非认证错误时显示提示
    if (error.message && !error.message.includes('401') && !error.message.includes('无效的会话')) {
      ElMessage.warning('试卷列表暂时无法加载，请稍后重试')
    }
  }
}

const loadCourses = async () => {
  try {
    const response = await getMyCourses()
    if (response && response.code === 200 && response.data) {
      courses.value = response.data
    }
  } catch (error) {
    console.warn('加载课程列表失败:', error)
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理，重置到第一页
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const createNewPaper = () => {
  isEditing.value = false
  paperForm.value = {
    name: '',
    description: '',
    courseId: null,
    duration: 120,
    totalScore: 100,
    startTime: '',
    endTime: '',
    settings: ['showScore']
  }
  examTimeRange.value = []
  showPaperDialog.value = true
}

const editPaper = (paper) => {
  isEditing.value = true
  paperForm.value = { ...paper }
  examTimeRange.value = paper.startTime && paper.endTime ? 
    [paper.startTime, paper.endTime] : []
  showPaperDialog.value = true
}

const savePaper = async () => {
  try {
    await paperFormRef.value.validate()
    
    saving.value = true
    
    // 处理时间范围
    if (examTimeRange.value && examTimeRange.value.length === 2) {
      paperForm.value.startTime = examTimeRange.value[0]
      paperForm.value.endTime = examTimeRange.value[1]
    }
    
    // 构建后端需要的数据格式
    const examData = {
      title: paperForm.value.name,
      description: paperForm.value.description,
      startTime: paperForm.value.startTime,
      endTime: paperForm.value.endTime,
      durationMinutes: paperForm.value.duration,
      courseId: 1, // 暂时固定为1，后续可以从用户选择获取
      questions: [] // 暂时为空，后续需要添加题目选择功能
    }
    
    if (isEditing.value) {
      examData.examId = editingQuestion.value?.id
      const response = await updatePaper(examData)
      if (response.code === 200) {
        ElMessage.success('试卷更新成功')
      } else {
        ElMessage.error(response.message || '更新试卷失败')
      }
    } else {
      const response = await createPaper(examData)
      if (response.code === 200) {
        ElMessage.success('试卷创建成功')
      } else {
        ElMessage.error(response.message || '创建试卷失败')
      }
    }
    
    showPaperDialog.value = false
    loadPapers()
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('保存试卷失败:', error)
      ElMessage.error(isEditing.value ? '更新试卷失败' : '创建试卷失败')
    }
  } finally {
    saving.value = false
  }
}





const previewPaper = (paper) => {
  previewPaperData.value = paper
  showPreviewDialog.value = true
}



const importPaper = () => {
  // 导入试卷逻辑
  ElMessage.info('导入功能开发中')
}

const publishPaperAction = async (paper) => {
  try {
    await ElMessageBox.confirm(
      '确定要发布此试卷吗？发布后学生将可以看到并参与考试。',
      '确认发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    paper.status = 'published'
    ElMessage.success('试卷发布成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布试卷失败')
    }
  }
}

const startExam = async (paper) => {
  try {
    await ElMessageBox.confirm(
      '确定要开始此次考试吗？开始后学生将可以进入考试。',
      '确认开始考试',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    paper.status = 'active'
    ElMessage.success('考试已开始')
  } catch (error) {
    // 用户取消
  }
}

const viewResults = (paper) => {
  // 查看考试结果
  ElMessage.info('跳转到结果页面')
}

const viewAnalysis = (paper) => {
  // 查看数据分析
  ElMessage.info('跳转到分析页面')
}

const deletePaperAction = async (paper) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除试卷「${paper.name}」吗？此操作将同时删除考试安排和考试，不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 先删除考试安排
    const assignmentResponse = await deleteExamAssignment({ assignmentId: paper.id })
    if (assignmentResponse.code === 200) {
      // 再删除考试
      const examResponse = await deletePaper(paper.examId)
      if (examResponse.code === 200) {
        ElMessage.success('试卷删除成功')
        loadPapers()
      } else {
        ElMessage.error(examResponse.message || '删除考试失败')
      }
    } else {
      ElMessage.error(assignmentResponse.message || '删除考试安排失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除试卷失败:', error)
      ElMessage.error('删除试卷失败')
    }
  }
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

onMounted(async () => {
  await loadCourses()
  loadPapers()
})
</script>

<style lang="scss" scoped>
.papers-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  
  .header-left {
    h1 {
      font-size: 28px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 8px;
    }
    
    p {
      color: var(--neutral-500);
      font-size: 16px;
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }
  
  &.stat-active {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    transform: translateY(-3px);
    border: 2px solid var(--el-color-primary);
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    i {
      font-size: 20px;
      color: white;
    }
  }
  
  &.total .stat-icon {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  }
  
  &.active .stat-icon {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  }
  

  
  &.finished .stat-icon {
    background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  }
  
  .stat-content {
    h3 {
      font-size: 24px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 4px;
    }
    
    p {
      color: var(--neutral-500);
      font-size: 14px;
    }
  }
}

.search-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .search-left {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    
    .el-input {
      width: 250px;
    }
    
    .el-select {
      width: 150px;
    }
  }
}

.papers-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.paper-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }
  

  
  &.published {
    border-left: 4px solid #f97316;
  }
  
  &.active {
    border-left: 4px solid #10b981;
  }
  
  &.finished {
    border-left: 4px solid #8b5cf6;
  }
}

.paper-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  
  .paper-title {
    flex: 1;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: var(--neutral-700);
      margin-bottom: 8px;
      line-height: 1.4;
    }
  }
  
  .paper-actions {
    margin-left: 12px;
  }
}

.paper-content {
  flex: 1;
  margin-bottom: 20px;
  
  .paper-description {
    margin-bottom: 16px;
    
    p {
      color: var(--neutral-600);
      font-size: 14px;
      line-height: 1.5;
    }
  }
  
  .paper-meta {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 16px;
    
    .meta-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 13px;
      color: var(--neutral-500);
      
      i {
        color: var(--neutral-400);
      }
    }
  }
  
  .paper-time {
    margin-bottom: 16px;
    
    .time-item {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      margin-bottom: 4px;
      
      .label {
        color: var(--neutral-500);
      }
      
      .value {
        color: var(--neutral-600);
      }
    }
  }
  
  .paper-subjects {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    
    .subject-tag {
      font-size: 11px;
    }
  }
}

.paper-footer {
  .paper-progress {
    margin-bottom: 16px;
    
    .progress-info {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: var(--neutral-600);
      margin-bottom: 8px;
      
      .percentage {
        font-weight: 600;
        color: var(--primary-color);
      }
    }
  }
  
  .paper-actions-bottom {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  
  i {
    font-size: 64px;
    color: var(--neutral-300);
    margin-bottom: 24px;
  }
  
  h3 {
    font-size: 20px;
    color: var(--neutral-500);
    margin-bottom: 12px;
  }
  
  p {
    color: var(--neutral-400);
    margin-bottom: 24px;
  }
}

.paper-preview {
  .preview-header {
    margin-bottom: 32px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--neutral-200);
    
    h2 {
      font-size: 24px;
      font-weight: 600;
      color: var(--neutral-700);
      margin-bottom: 12px;
    }
    
    .preview-meta {
      display: flex;
      gap: 24px;
      font-size: 14px;
      color: var(--neutral-600);
      margin-bottom: 12px;
    }
    
    .preview-description {
      p {
        color: var(--neutral-600);
        line-height: 1.6;
      }
    }
  }
  
  .preview-questions {
    max-height: 400px;
    overflow-y: auto;
    
    .preview-question {
      margin-bottom: 32px;
      padding: 20px;
      border: 1px solid var(--neutral-200);
      border-radius: 8px;
      
      .question-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        h4 {
          font-size: 16px;
          font-weight: 600;
          color: var(--neutral-700);
        }
      }
      
      .question-content {
        .question-text {
          font-size: 15px;
          line-height: 1.6;
          color: var(--neutral-700);
          margin-bottom: 16px;
        }
        
        .question-options {
          .option-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 0;
            
            .option-label {
              font-weight: 600;
              color: var(--neutral-600);
              min-width: 20px;
            }
            
            .option-text {
              color: var(--neutral-700);
            }
          }
        }
        
        .fill-blanks,
        .essay-area {
          p {
            color: var(--neutral-600);
            margin-bottom: 12px;
          }
          
          .answer-area {
            padding: 20px;
            background: var(--neutral-50);
            border: 1px dashed var(--neutral-300);
            border-radius: 6px;
            color: var(--neutral-500);
            text-align: center;
          }
        }
      }
    }
  }
}

.danger {
  color: var(--error-color) !important;
}

@media (max-width: 768px) {
  .search-section {
    .search-left {
      flex-direction: column;
      width: 100%;
      
      .el-input,
      .el-select {
        width: 100%;
      }
    }
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    
    .header-right {
      justify-content: flex-start;
    }
  }
  
  .papers-grid {
    grid-template-columns: 1fr;
  }
  
  .paper-meta {
    grid-template-columns: 1fr;
  }
  
  .paper-actions-bottom {
    flex-direction: column;
    
    .el-button {
      width: 100%;
    }
  }
}
</style>